package cn.bonoon.controllers;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.batatasframework.rawdata.RawdataDefinition;
import org.batatasframework.rawdata.RawdataImportedResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.bonoon.core.RawdataExportService;
import cn.bonoon.core.RawdataImportService;
import cn.bonoon.core.RawdataItem;
import cn.bonoon.core.RawdataStreamService;
import cn.bonoon.entities.RawdataExportEntity;
import cn.bonoon.entities.RawdataImportEntity;
import cn.bonoon.kernel.events.PanelEvent;
import cn.bonoon.kernel.security.LogonUser;
import cn.bonoon.kernel.support.IOperator;
import cn.bonoon.kernel.web.controllers.AbstractPanelController;
import cn.bonoon.kernel.web.models.PanelModel;
/**
 * 存疑/退回处理
 * @author zjb
 *
 */
@Controller
@RequestMapping("s/rdi/{catalog}!doubt")
public class RawdataDoubtController extends AbstractPanelController{


	private @Autowired RawdataStreamService rawdataStreamService;  
	
	private @Autowired RawdataImportService rawdataImportService;
	
	private @Autowired RawdataExportService rawdataExportService;
	
	private String catalog;
	
	@ModelAttribute
	public void setCatalog(@PathVariable("catalog") String catalog) {
		this.catalog = catalog;
	}

	@Override
	protected void onLoad(PanelEvent event) throws Exception {
		PanelModel model = event.getModel();
		IOperator user = event.getUser();
		List<RawdataItem> items = rawdataStreamService.myItems(user, catalog);
		model.addObject("items", items);
		model.addObject("catalog", catalog);

		event.setVmPath("plugs-rawdata/doubt");
	}
	@ResponseBody
	@RequestMapping(value="!{key}/getItems.list",method = {RequestMethod.POST,RequestMethod.GET})
	public List<RawdataImportItem> getDoubtExportItems(String key){
		if (key==null) {
			return null;
		}
		RawdataImportedResult result=rawdataStreamService.getDoubtBy(getUser(), catalog, key,null, null);
		List<RawdataImportEntity> list=result.getImportList();
		List<RawdataImportItem> itemList=new ArrayList<>();
		for (RawdataImportEntity rawdataImportEntity : list) {
			RawdataImportItem importItem=new RawdataImportItem();
			importItem.setId(rawdataImportEntity.getId());
			importItem.setCreateAt((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(rawdataImportEntity.getCreateAt()));
			importItem.setName(rawdataImportEntity.getName());
			importItem.setTitle(rawdataImportEntity.getTitle());
			itemList.add(importItem);
		}
		return itemList;
	}
	@RequestMapping(value="!{key}/load.do",method = {RequestMethod.POST,RequestMethod.GET})
	public String loadItem(Model model, @PathVariable("code") String code){
		model.addAttribute("layout", "layout-empty.vm");
		IOperator user = getUser();
		RawdataImportedResult result = rawdataStreamService.getDoubtBy(user, catalog, code,null, null);
		model.addAttribute("items", result.getItems());
		model.addAttribute("selectable",true);
		return result.getVmpath();
	}
	// 查看
	@RequestMapping(value="!{key}/detail.doubtdlg",method = {RequestMethod.POST,RequestMethod.GET})
	public String detailPic(Model model, Long id,String code) {
		model.addAttribute("layout", "layout-empty.vm");
		IOperator user = getUser();
		model.addAttribute("subject", id);
		RawdataImportEntity  entity = rawdataImportService.get(id);
		RawdataImportedResult result = rawdataStreamService.getDoubtBy(user, catalog, code,id, null);
		model.addAttribute("items", result.getItems());
		model.addAttribute("selectable",true);
		model.addAttribute("detailItemPath",result.getVmpath());
		//前台需要的参数
		model.addAttribute("haohaochi",code);
		model.addAttribute("vm","doubt");
		model.addAttribute("result",false);
		model.addAttribute("size",result.getItems().size());
		model.addAttribute("materials",entity.getMaterials());
		model.addAttribute("materialsSize",entity.getMaterials().size() );
		return "plugs-rawdata/details";
		
	}
	@RequestMapping("!{key}/page.change")
	public String page(@RequestParam("subject") Long id,int start,int end,
			HttpServletRequest request, Model model) {
		RawdataImportEntity  entity = rawdataImportService.get(id);
//		List<RawdataImportMaterial> materials=entity.getMaterials();
		
	
		LogonUser user = getUser();
		RawdataDefinition def = rawdataStreamService.getDefinition(user, entity.getCatalog(), entity.getKey());
		model.addAttribute("selectable",true);

		RawdataImportedResult result = rawdataStreamService.getDoubtBy(user, entity.getCatalog(), entity.getKey(),id,null);
		List<Object>  list=result.getItems().subList(start, end);
		model.addAttribute("items",list );
		model.addAttribute("size",list.size() );
		model.addAttribute("layout", "layout-empty.vm");
		return def.getVmpath();
	}
	//全部导出Excel
	@RequestMapping(value = "!{key}/download.do")
	public void download(HttpServletResponse response,
			HttpServletRequest request, 
			Long id,String code) {
		IOperator user = getUser();
		RawdataImportedResult result = rawdataStreamService.getDoubtBy(user, catalog, code,id,null);
		RawdataImportEntity entity=rawdataImportService.get(id);
		RawdataDefinition def = rawdataStreamService.getDefinition(user, entity.getCatalog(), entity.getKey());
		List<Object> list=result.getItems();
		String[] ids=new String[list.size()];
		int i=0;
		for (Object object : list) {
			ids[i]=String.valueOf(getFieldValueByName("id",object));
			i++;
		}
		RawdataExportEntity exportEntity=rawdataExportService.addExportEntity(user, ids, def);
		def.getParser().excelFormat(list, response, request,exportEntity.getDownloadName().split("\\.")[0]);
		
	}
	//勾选导出Excel
	@RequestMapping(value = "!{key}/selectdownload.do")
	public void selectdownload(HttpServletResponse response,
			HttpServletRequest request, 
			Long id,String[] SelectOut) {
		IOperator user = getUser();
		RawdataImportEntity entity=rawdataImportService.get(id);
		//String[] getIds=request.getParameterValues("");
		RawdataImportedResult result = rawdataStreamService.getDoubtBy(user, entity.getCatalog(), entity.getKey(),id, SelectOut);
		RawdataDefinition def = rawdataStreamService.getDefinition(user, entity.getCatalog(), entity.getKey());
		List<Object> list=result.getItems();
		String[] ids=new String[list.size()];
		int i=0;
		for (Object object : list) {
			ids[i]=String.valueOf(getFieldValueByName("id",object));
			i++;
		}
		RawdataExportEntity exportEntity=rawdataExportService.addExportEntity(user, ids, def);
		def.getParser().excelFormat(list, response, request,exportEntity.getDownloadName().split("\\.")[0]);
		
	}
	/** 
	 * 根据属性名获取属性值 
	 * */  
   private Object getFieldValueByName(String fieldName, Object o) {  
       try {    
           String firstLetter = fieldName.substring(0, 1).toUpperCase();    
           String getter = "get" + firstLetter + fieldName.substring(1);    
           Method method = o.getClass().getMethod(getter, new Class[] {});    
           Object value = method.invoke(o, new Object[] {});    
           return value;    
       } catch (Exception e) {    
           return null;    
       }    
   }  
}
